<template>
  <el-tabs v-model="activeTab" class="demo-tabs" type="border-card">
    <el-tab-pane label="密码登录" name="first">
      <el-form class="login-form"
             :rules="loginRules"
             ref="loginFormRef"
             :model="loginForm"
             >
      <el-form-item prop="userId">
        <el-input size="large"
                  v-model="loginForm.userId"
                  auto-complete="off"
                  placeholder="请输入手机号">
          <template #prepend>
            <i class="icon-yonghu"></i>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input size="large"
                  :type="passwordType"
                  v-model="loginForm.password"
                  auto-complete="off"
                  :placeholder="$t('login.password')">
          <template #suffix>
            <i class="el-icon-view el-input__icon"
               @click="showPassword"></i>
          </template>
          <template #prepend>
            <i class="icon-mima"></i>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="code">
        <el-input size="large"
                  @keyup.enter="handlePasswordLogin"
                  :maxlength="code.len"
                  v-model="code.value"
                  auto-complete="off"
                  :placeholder="$t('login.code')">
          <template #prepend>
            <i class="icon-yanzhengma"></i>
          </template>

          <template #append>
            <div class="login-code">
            <span class="login-code-img"
                  @click="refreshCode"
                  v-if="code.type === 'text'">{{code.value}}</span>
              <img :src="code.src"
                   class="login-code-img"
                   @click="refreshCode"
                   v-else />
            </div>
          </template>
        </el-input>
      </el-form-item>
      <div>
        <el-link href="/register">注册账号</el-link>
        <el-link href="/forget">忘记密码</el-link>
      </div>
      <el-form-item>
        <el-button type="primary"
                   size="small"
                   @click.prevent="handlePasswordLogin"
                   class="login-submit">{{$t('login.submit')}}</el-button>
      </el-form-item>
    </el-form>
    </el-tab-pane>
    <el-tab-pane label="短信登录" name="second">
      <el-form class="login-form"
               status-icon
               :rules="messageLoginRules"
               ref="messageFormRef"
               :model="messageLoginForm"
               label-width="0">
        <el-form-item prop="userId">
          <el-input v-model="messageLoginForm.userId"
                    auto-complete="off"
                    placeholder="请输入手机号">
            <template #prepend>
              <i class="icon-yonghu"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkCode">
          <el-input
              v-model="messageLoginForm.checkCode"
              placeholder="请输入短信验证码"
              class="input-with-select"
          >
            <template #prepend>
              <el-icon size="18px"><chat-dot-round /></el-icon>
            </template>
            <template #append>
              <el-button @click="getCode">获取验证码</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     size="small"
                     @click.prevent="handleMsLogin"
                     class="login-submit">{{$t('login.submit')}}</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>

</template>

<script setup>
import {ref, reactive, getCurrentInstance, computed} from 'vue';
import { randomLenNum } from "../../utils/util";
import {ChatDotRound} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';
import {getCodeApi} from '../../api/login';
import {validatenull} from '../../utils/validate';

const { proxy } = getCurrentInstance(); //获取上下文实例，proxy=vue2的this

const activeTab = ref('first')

const messageFormRef = ref(null)
const messageLoginRules = reactive({
  userId: [{required: true, message: "请输入手机号", trigger: "blur"}],
  checkCode: [{required: true, message: "请输入验证码", trigger: "blur"}]
})
const messageLoginForm = ref({
  userId:'',
  checkCode:'',
})

const loginForm=reactive({
  userId: "13225802370",
  password: "123",
  code: "",
  redomStr: ""
})

const code=reactive({
  src: "",
  value: "",
  len: 4,
  type: "text"
})

const refreshCode = () => {
  code.type === "text"
      ? (code.value = randomLenNum(code.len))
      : (code.src = `/${loginForm.redomStr}`);
}
refreshCode()

const passwordType=ref("password")

const showPassword = () => {
  passwordType.value === ""
      ? (passwordType.value = "password")
      : (passwordType.value = "");
}

const validateCode = (rule, value, callback) => {
  if (code.value !== value) {
    loginForm.code = "";
    refreshCode();
    callback(new Error("请输入正确的验证码"));
  } else {
    callback();
  }
};

const loginRules=reactive({
  userId: [
    { required: true, message: "请输入手机号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码长度为4位", trigger: "blur" },
    { required: true, trigger: "blur", validator: validateCode }
  ]
})

const loginFormRef=ref(null)
/**
 * 使用账号密码登录
 */
const handlePasswordLogin = () => {
  loginForm.code = code.value
  loginFormRef.value.validate(valid => {
    if (valid) {
      loginForm.password = proxy.$md5(loginForm.password)
      proxy.$store.dispatch("LoginByUsername", loginForm).then(() => {
        ElMessage.success("登录成功！")
        proxy.$router.push("/wel/index");
      });
    }})
}

/**
 * 获取验证码
 */
const getCode = () =>{
  if(!validatenull(messageLoginForm.value.userId)){
    getCodeApi(messageLoginForm.value.userId).then(res=> {
      if(res.data.responseSuccess){
        ElMessage.success("发送成功！");
      }
    })
  }else {
    ElMessage.error("请输入手机号码！");
  }
}

/**
 * 使用短信验证码登录
 */
const handleMsLogin = () => {
  messageFormRef.value.validate(valid => {
    if (valid) {
      proxy.$store.dispatch("LoginByPhone", messageLoginForm.value).then(() => {
        ElMessage.success("登录成功！")
        proxy.$router.push("/wel/index");
      });
    }
  })
}
</script>

<style scoped>
.el-link {
  margin-right: 8px;
}
.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
/deep/ .el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active{
  color: red;
}

/deep/ .login-form .el-input input{
  padding-left: 0px;
}

/deep/ .login-form .el-form-item{
  margin-bottom: 16px;
}
</style>
